package cn.four.hqServer.modules.cardBinding.service.impl;

import cn.four.hqServer.common.entity.HqCardInfo;
import cn.four.hqServer.common.entity.HqUserInfo;
import cn.four.hqServer.common.enums.CardStatusEnum;
import cn.four.hqServer.common.result.Result;
import cn.four.hqServer.modules.balance.service.LycCardInfoService;
import cn.four.hqServer.modules.balance.service.LycUserInfoService;
import cn.four.hqServer.modules.cardBinding.dto.UserValidDto;
import cn.four.hqServer.modules.cardBinding.mapper.CardRebindMapper;
import cn.four.hqServer.modules.cardBinding.service.CardRebindService;
import cn.four.hqServer.modules.cardBinding.service.CardWithdrawService;
import cn.four.hqServer.modules.userlogin.vo.UserLoginVo;
import cn.four.hqServer.modules.userregister.utils.DcNumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author znb
 * @since 2023-02-23
 */
@Service
public class CardRebindServiceImpl extends ServiceImpl<CardRebindMapper, HqCardInfo> implements CardRebindService {


    @Resource
    private CardWithdrawService cardWithdrawService;

    @Resource
    private LycCardInfoService cardInfoService;

    @Resource
    private LycUserInfoService userInfoService;


    @Transactional
    @Override
    public Result rebind(UserValidDto userValidDto) {
        String userId = userValidDto.getUserId();
        /**
         * 判断身份证是否存在且正确
         */
        HqUserInfo userInfo = userInfoService.getUserInfo(userId);

        //用session来获取当前登录用户身份证
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        UserLoginVo loginUser = (UserLoginVo) request.getSession().getAttribute("userInfo");

        if(loginUser!=null) {
            //用于判断当前登录用户身份证与输入的身份证是否相符，就算输入身份证在数据库中有，也只能重新登录才能绑定。避免其他人也能重新绑定别人银行卡
            if (userInfo != null && userId.equals(loginUser.getUserId())) {

                /**
                 *             查询没有注销的银行卡信息
                 */
                HqCardInfo cardInfo = this.getOne(new QueryWrapper<HqCardInfo>().eq("user_id", userInfo.getUserId()).
                        ne("state",CardStatusEnum.logout.getCode()));
                /**
                 * 判断与身份证对应银行卡是否正确
                 */
                if (cardInfo != null && cardInfo.getCardId().equals(userValidDto.getCardId())) {
                    /**
                     * 判断支付密码是否正确
                     */
                    String salt = (userInfo.getSalt() != null) ? userInfo.getSalt() : "";

                    //测试
//                    cardInfoService.update(new UpdateWrapper<HqCardInfo>().eq("user_id", userValidDto.getUserId())
//                            .set("password", DigestUtils.md5Hex(("123451" + salt))));

                    String validPassword = DigestUtils.md5Hex((userValidDto.getPassword() + salt));
                    if (validPassword.equals(cardInfo.getPassword())) {
                        /**
                         * 重新綁定： 将原来银行卡信息（注销），，再生成新的
                         */


                        //注销银行卡
                        Result result = cardWithdrawService.withdraw(userValidDto.getCardId());

                        //注销成功，重新生成银行卡号以及设定新密码
                        if(result.getCode() == 200) {
                            DcNumberUtil numberUtil = DcNumberUtil.getInstance();
                            String idNumber = numberUtil.generateDCNumber();
                            HqCardInfo hqCardInfo = new HqCardInfo();
                            hqCardInfo.setCardId(idNumber);
                            hqCardInfo.setUserId(userId);
                            hqCardInfo.setPassword(DigestUtils.md5Hex((userValidDto.getPassword() + salt)));
                            hqCardInfo.setBalance(new BigDecimal(0.0));
                            hqCardInfo.setState(0);
                            hqCardInfo.setCreateTime(LocalDateTime.now());
                            hqCardInfo.setUpdateTime(LocalDateTime.now());
                            cardInfoService.save(hqCardInfo);

                            //测试业务出现异常，数据库是否回滚
//                            int a =1/0;
                            return Result.success(200, "重新绑定成功，新生成的银行卡号是" + idNumber, idNumber);
                        }
                        else return Result.error(result.getMessage());
                    } else return Result.error("支付密码错误");
                } else return Result.error("银行卡信息错误");
            } else return Result.error("身份证信息不符");
        } else return Result.error("请登录再操作");
    }
}